import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import './App.css'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'

export default class App extends Component {
    constructor(){
        super()
        // 改变事件回调函数this的指向，指向当前实例对象
        this.addTodo = this.addTodo.bind(this)
        this.deleteTodo = this.deleteTodo.bind(this)
        this.changeDone = this.changeDone.bind(this)
        this.checkAll = this.checkAll.bind(this)
        this.deleteDone = this.deleteDone.bind(this)
    }
    state = {
        todos:[
            {
                id:1,
                title:'吃饭',
                isDone:true
            },
            {
                id:2,
                title:'睡觉',
                isDone:true
            }
        ]
    }
    /**
     * 修改状态方式二：
     * 
     */
    changeDone(todo){
        todo.isDone = !todo.isDone
        this.forceUpdate();
    }
    /**
     * 添加todo
     * 子传父
     * 第一步：父组件定义方法
     */
    addTodo(title){
        console.log('App title: ', title);
        let todo = {
            // 0-9 a-z 26  36
            // id:Math.random().toString(36).slice(2),
            id:nanoid(),
            title,
            isDone:false
        }
        // 将todo放到todos中
        this.setState({
            todos:[todo,...this.state.todos]
        })
    }
    /**
     * 全选反选
     * @param {*} isDone 
     */
    checkAll(isDone){
        let todos = this.state.todos.map(todo=>{
            todo.isDone = isDone
            return todo;
        })

        this.setState({
            todos
        })
    }
    /**
     *  删除已完成
     *  deleteDone
     */
    deleteDone(){
        if(!window.confirm('确定删除已完成的代办事项么？')) return;
        let todos = this.state.todos.filter(todo=>!todo.isDone)
        this.setState({
            todos
        })
    }
    /**
     * 根据id删除todo
     * @returns 
     */
    deleteTodo(id){
        if(!window.confirm('确定删除么?')) return;
        console.log('app id: ', id);
        // 根据id删除数据，不是这个id的保留
        let todos = this.state.todos.filter(todo=>todo.id !== id)
        this.setState({
            todos:todos
        })
    }
    render() {
        let {todos} = this.state;
        return (
            <div className="todo-container">
                <div className="todo-wrap">
                    {/* 子传父第二步，将方法传递给子组件 */}
                    <Header addTodo={this.addTodo} todos={todos}/>
                    <List todos={todos} deleteTodo={this.deleteTodo} changeDone={this.changeDone}/>
                    <Footer todos={todos} checkAll={this.checkAll} deleteDone={this.deleteDone}/>
                </div>
            </div>
        )
    }
}
